package com.yupi.springbootinit.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.springbootinit.annotation.AuthCheck;
import com.yupi.springbootinit.bizmq.BIMessageProducer;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.DeleteRequest;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.constant.CommonConstant;
import com.yupi.springbootinit.constant.UserConstant;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.exception.ThrowUtils;
import com.yupi.springbootinit.manager.AiManager;
import com.yupi.springbootinit.manager.RedisLimiterManager;
import com.yupi.springbootinit.model.dto.chart.*;
import com.yupi.springbootinit.model.entity.Chart;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.enums.ChartStatusEnum;
import com.yupi.springbootinit.model.vo.BiResponse;
import com.yupi.springbootinit.service.ChartService;
import com.yupi.springbootinit.service.UserService;
import com.yupi.springbootinit.sse.SseService;
import com.yupi.springbootinit.utils.ExcelUtils;
import com.yupi.springbootinit.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

import static com.yupi.springbootinit.constant.CommonConstant.YUCONGMING_AI_MODE_ID;

/**
 * 帖子接口
 *
 * @author <a href="https://gitee.com/hehui666">小老板</a>
 * @from <a href="https://blog.xiaob6.cn">小老板的blog</a>
 */
@RestController
@RequestMapping("/chart")
@Slf4j
public class ChartController {

    @Resource
    private ChartService chartService;

    @Resource
    private UserService userService;

    @Resource
    private AiManager aiManager;
    @Resource
    private RedisLimiterManager redisLimiterManager;
    // region 增删改查
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;
    @Resource
    private BIMessageProducer biMessageProducer;

    @Resource
    private SseService sseService;

    /**
     * 创建图表
     *
     * @param chartAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addChart(@RequestBody ChartAddRequest chartAddRequest, HttpServletRequest request) {
        if (chartAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartAddRequest, chart);
        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());
        boolean result = chartService.save(chart);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newchartId = chart.getId();
        return ResultUtils.success(newchartId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deletechart(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Chart oldchart = chartService.getById(id);
        ThrowUtils.throwIf(oldchart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldchart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = chartService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param chartUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatechart(@RequestBody ChartUpdateRequest chartUpdateRequest) {
        if (chartUpdateRequest == null || chartUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartUpdateRequest, chart);
        long id = chartUpdateRequest.getId();
        // 判断是否存在
        Chart oldchart = chartService.getById(id);
        ThrowUtils.throwIf(oldchart == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Chart> getChartById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = chartService.getById(id);
        if (chart == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(chart);
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param chartQueryRequest
     * @return
     */
    //    @PostMapping("/list/page")
    //    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    //    public BaseResponse<Page<Chart>> listchartByPage(@RequestBody ChartQueryRequest chartQueryRequest) {
    //        long current = chartQueryRequest.getCurrent();
    //        long size = chartQueryRequest.getPageSize();
    //        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
    //                getQueryWrapper(chartQueryRequest));
    //        return ResultUtils.success(chartPage);
    //    }

    /**
     * 分页获取列表（封装类）
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<Chart>> listChartByPage(@RequestBody ChartQueryRequest chartQueryRequest, HttpServletRequest request) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size), getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page")
    public BaseResponse<Page<Chart>> listMyChartByPage(@RequestBody ChartQueryRequest chartQueryRequest, HttpServletRequest request) {
        if (chartQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        chartQueryRequest.setUserId(loginUser.getId());
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size), getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    // endregion


    private QueryWrapper<Chart> getQueryWrapper(ChartQueryRequest chartQueryRequest) {
        QueryWrapper<Chart> queryWrapper = new QueryWrapper<>();
        if (chartQueryRequest == null) {
            return queryWrapper;
        }
        String sortField = chartQueryRequest.getSortField();
        String sortOrder = chartQueryRequest.getSortOrder();
        Long id = chartQueryRequest.getId();
        String goal = chartQueryRequest.getGoal();
        String chartType = chartQueryRequest.getChartType();
        String name = chartQueryRequest.getName();
        Long userId = chartQueryRequest.getUserId();

        queryWrapper.eq(id != null && id > 0, "id", id);
        queryWrapper.eq(StringUtils.isNotBlank(goal), "goal", goal);
        queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(chartType), "chartType", chartType);
        queryWrapper.eq("isDelete", false);

        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        return queryWrapper;
    }


    /**
     * 编辑表的基本信息
     *
     * @param chartBaseInfoEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit/chartBaseInfo")
    public BaseResponse<Boolean> editChartBaseInfo(@RequestBody ChartBaseInfoEditRequest chartBaseInfoEditRequest, HttpServletRequest request) {
        if (chartBaseInfoEditRequest == null || chartBaseInfoEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartBaseInfoEditRequest, chart);
        User loginUser = userService.getLoginUser(request);
        long id = chartBaseInfoEditRequest.getId();
        // 判断是否存在
        Chart oldchart = chartService.getById(id);
        ThrowUtils.throwIf(oldchart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldchart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }


    /**
     * 编辑表的原始信息
     *
     * @param chartRawDataEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit/ChartRawData")
    public BaseResponse<Boolean> editChartRawData(@RequestBody ChartRawDataEditRequest chartRawDataEditRequest, HttpServletRequest request) {
        if (chartRawDataEditRequest == null || chartRawDataEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        User loginUser = userService.getLoginUser(request);
        long chartId = chartRawDataEditRequest.getId();
        //         判断表是否存在
        Chart oldchart = chartService.getById(chartId);
        //        ThrowUtils.throwIf(oldchart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldchart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        List<LinkedHashMap<String, Object>> modifiedData = chartRawDataEditRequest.getModifiedData();
        int updateSucceedNum = chartService.upDateChartRawData(chartId, modifiedData);
        return ResultUtils.success(updateSucceedNum > 0);
    }

    /**
     * 生成图表（同步）
     *
     * @param multipartFile
     * @param genCharByAiRequest
     * @param request
     * @return
     */
    @PostMapping("/gen")
    public BaseResponse<BiResponse> genChartByAi(@RequestPart("file") MultipartFile multipartFile, GenCharByAiRequest genCharByAiRequest, HttpServletRequest request) {

        String name = genCharByAiRequest.getName();
        String goal = genCharByAiRequest.getGoal();
        String chartType = genCharByAiRequest.getChartType();
        //校验参数
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空");
        ThrowUtils.throwIf(StringUtils.isNotBlank(name) && name.length() > 100, ErrorCode.PARAMS_ERROR, "名称过长");
        //文件
        String originalFilename = multipartFile.getOriginalFilename();
        long size = multipartFile.getSize();
        final long ONE_MB = 1024 * 1024;
        ThrowUtils.throwIf(size > ONE_MB, ErrorCode.PARAMS_ERROR, "文件超过 1MB");
        List<String> validFileSuffix = Arrays.asList("xlsx", "xls");
        String suffix = FileUtil.getSuffix(originalFilename);

        ThrowUtils.throwIf(!validFileSuffix.contains(suffix), ErrorCode.PARAMS_ERROR, "文件后缀非法");


        User loginUser = userService.getLoginUser(request);
        //限流判断,每个用户一个限流器
        redisLimiterManager.doRateLimit("genChartByAi_" + loginUser.getId());


        //        分析需求:
        //        分析网站用户的增长情况
        //        原始数据:
        //        日期用户数
        //        1号,10
        //        2号,20
        //        3号30


        //用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：").append("\n");
        //拼接图标类型
        String userGoal = goal;
        if (StringUtils.isNotBlank(chartType)) {
            userGoal += goal + ",请使用" + chartType + "图标类型";
        }
        userInput.append(userGoal).append("\n");
        userInput.append("原始数据：").append("\n");
        //压缩后的数据
        String csvString = ExcelUtils.excelToCsv(multipartFile);
        userInput.append(csvString).append("\n");
        long modelId = 1768213859761868802L;
        String analyzeResult = aiManager.doChat(modelId, userInput.toString());
        String[] split = analyzeResult.split("【【【【【");
        if (split.length < 3) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "AI 生成错误");
        }
        String genChart = split[1].trim().replaceAll("'", "\"");
        String genResult = split[2].trim();
        //插入到数据库
        Chart chart = new Chart();
        chart.setName(name);
        chart.setGoal(goal);
        chart.setChartData(csvString);
        chart.setChartType(chartType);
        chart.setGenChart(genChart);
        chart.setGenResult(genResult);
        chart.setStatus(ChartStatusEnum.SUCCEED.status);
        chart.setUserId(loginUser.getId());
        boolean saveResult = chartService.save(chart);
        ThrowUtils.throwIf(!saveResult, ErrorCode.PARAMS_ERROR, "保存图表失败");
        BiResponse biResponse = new BiResponse();
        biResponse.setGenChart(genChart);
        biResponse.setGenResult(genResult);
        biResponse.setChartId(chart.getId());


        //重试
        //        Callable<Boolean> callable = new Callable<Boolean>() {
        //            public Boolean call() throws Exception {
        //                return split.length < 3; // do something useful here
        //            }
        //        };
        //
        //        Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
        //                .retryIfResult(Predicates.<Boolean>isNull())
        //                .retryIfExceptionOfType(IOException.class)
        //                .retryIfRuntimeException()
        //                .withStopStrategy(StopStrategies.stopAfterAttempt(3))
        //                .build();
        //        try {
        //            retryer.call(callable);
        //        } catch (RetryException e) {
        //            e.printStackTrace();
        //        } catch (ExecutionException e) {
        //            e.printStackTrace();
        //        }
        //

        return ResultUtils.success(biResponse);
    }


    /**
     * 生成图表（异步）
     *
     * @param multipartFile
     * @param genCharByAiRequest
     * @param request
     * @return
     */
    @PostMapping("/gen/async")
    public BaseResponse<BiResponse> genChartByAiAsync(@RequestPart("file") MultipartFile multipartFile, GenCharByAiRequest genCharByAiRequest, HttpServletRequest request) {

        String name = genCharByAiRequest.getName();
        String goal = genCharByAiRequest.getGoal();
        String chartType = genCharByAiRequest.getChartType();
        //校验参数
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空");
        ThrowUtils.throwIf(StringUtils.isNotBlank(name) && name.length() > 100, ErrorCode.PARAMS_ERROR, "名称过长");
        //文件
        String originalFilename = multipartFile.getOriginalFilename();
        long size = multipartFile.getSize();
        final long ONE_MB = 1024 * 1024;
        ThrowUtils.throwIf(size > ONE_MB, ErrorCode.PARAMS_ERROR, "文件超过 1MB");
        List<String> validFileSuffix = Arrays.asList("xlsx", "xls");
        String suffix = FileUtil.getSuffix(originalFilename);

        ThrowUtils.throwIf(!validFileSuffix.contains(suffix), ErrorCode.PARAMS_ERROR, "文件后缀非法");


        User loginUser = userService.getLoginUser(request);
        //限流判断,每个用户一个限流器
        redisLimiterManager.doRateLimit("genChartByAi_" + loginUser.getId());


        //        分析需求:
        //        分析网站用户的增长情况
        //        原始数据:
        //        日期用户数
        //        1号,10
        //        2号,20
        //        3号30


        //用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：").append("\n");
        //拼接图标类型
        String userGoal = goal;
        if (StringUtils.isNotBlank(chartType)) {
            userGoal += goal + ",请使用" + chartType + "图标类型";
        }
        userInput.append(userGoal).append("\n");
        userInput.append("原始数据：").append("\n");
        //压缩后的数据
        String csvString = ExcelUtils.excelToCsv(multipartFile);
        userInput.append(csvString).append("\n");

        //1.先把图表保存到数据库中
        Chart chart = new Chart();
        chart.setName(name);
        chart.setGoal(goal);
        chart.setChartData(csvString);
        chart.setChartType(chartType);
        chart.setUserId(loginUser.getId());
        //todo 状态修改为枚举
        // 设置任务状态为排队中
        chart.setStatus(ChartStatusEnum.WAIT.getValue());
        boolean save = chartService.save(chart);
        ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "保存图表失败");

        //
        CompletableFuture.runAsync(() -> {
            Chart updateChart = new Chart();
            updateChart.setId(chart.getId());
            updateChart.setStatus(ChartStatusEnum.RUNNING.getValue());
            boolean b = chartService.updateById(updateChart);
            if (!b) {
                handleChartUpdateError(chart.getId(), "更新图表'执行中'状态失败");
                return;
            }
            //调用ai

            String analyzeResult = aiManager.doChat(YUCONGMING_AI_MODE_ID, userInput.toString());
            String[] split = analyzeResult.split("【【【【【");
            if (split.length < 3) {
                handleChartUpdateError(chart.getId(), "AI 生成错误");
                return;
            }
            String genChart = split[1].trim().replaceAll("'", "\"");
            String genResult = split[2].trim();
            //调用ai得到结果之后,再更新一次
            Chart updateChartResult = new Chart();
            updateChartResult.setId(chart.getId());
            updateChartResult.setGenChart(genChart);
            updateChartResult.setGenResult(genResult);
            updateChartResult.setStatus(ChartStatusEnum.SUCCEED.getValue());
            boolean b1 = chartService.updateById(updateChartResult);
            if (!b1) {
                handleChartUpdateError(chart.getId(), "更新图表'成功'状态失败");

            }
        }, threadPoolExecutor);

        BiResponse biResponse = new BiResponse();
        biResponse.setChartId(chart.getId());
        return ResultUtils.success(biResponse);
    }

    /**
     * 生成图表（异步消息队列）
     *
     * @param multipartFile
     * @param genCharByAiRequest
     * @param request
     * @return
     */
    @PostMapping("/gen/async/mq")
    public BaseResponse<BiResponse> genChartByAiAsyncMQ(@RequestPart("file") MultipartFile multipartFile, GenCharByAiRequest genCharByAiRequest, HttpServletRequest request) {


        String name = genCharByAiRequest.getName();
        String goal = genCharByAiRequest.getGoal();
        String chartType = genCharByAiRequest.getChartType();
        //校验参数
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空");
        ThrowUtils.throwIf(StringUtils.isNotBlank(name) && name.length() > 100, ErrorCode.PARAMS_ERROR, "名称过长");
        //文件
        String originalFilename = multipartFile.getOriginalFilename();
        long size = multipartFile.getSize();
        final long ONE_MB = 1024 * 1024;
        ThrowUtils.throwIf(size > ONE_MB, ErrorCode.PARAMS_ERROR, "文件超过 1MB");
        List<String> validFileSuffix = Arrays.asList("xlsx", "xls");
        String suffix = FileUtil.getSuffix(originalFilename);

        ThrowUtils.throwIf(!validFileSuffix.contains(suffix), ErrorCode.PARAMS_ERROR, "文件后缀非法");


        User loginUser = userService.getLoginUser(request);
        //限流判断,每个用户一个限流器
        redisLimiterManager.doRateLimit("genChartByAi_" + loginUser.getId());


        //用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：").append("\n");
        //拼接图标类型
        String userGoal = goal;
        if (StringUtils.isNotBlank(chartType)) {
            userGoal += goal + ",请使用" + chartType + "图标类型";
        }
        userInput.append(userGoal).append("\n");
        userInput.append("原始数据：").append("\n");
        //压缩后的数据
        String csvString = ExcelUtils.excelToCsv(multipartFile);
        userInput.append(csvString).append("\n");

        //1.先把图表保存到数据库中
        Chart chart = new Chart();
        chart.setName(name);
        chart.setGoal(goal);
        chart.setChartData(csvString);
        chart.setChartType(chartType);
        chart.setUserId(loginUser.getId());
        chart.setStatus(ChartStatusEnum.WAIT.getValue());
        boolean save = chartService.save(chart);
        ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "保存图表失败");
        //-------------分表

        //保存图表原始数据-根据表头建表-根据表体插入
        List<Map<Integer, String>> excelToTableList = ExcelUtils.excelToTable(multipartFile);
        boolean isCreateChartRawDataTable = chartService.createAndInsert(chart.getId(), excelToTableList);
        ThrowUtils.throwIf(!isCreateChartRawDataTable, ErrorCode.SYSTEM_ERROR, "创建原始数据表失败：chartID：" + chart.getId());
        //将图表id发送到消息队列
        biMessageProducer.sendMessage(chart.getId().toString());

        BiResponse biResponse = new BiResponse();
        biResponse.setChartId(chart.getId());
        return ResultUtils.success(biResponse);
    }

    private void handleChartUpdateError(long chartId, String execMsg) {
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chartId);
        updateChartResult.setStatus(ChartStatusEnum.FAILED.getValue());
        updateChartResult.setExecMessage(execMsg);
        boolean save = chartService.save(updateChartResult);
        if (!save) {
            log.error("更新图表'失败'状态失败" + chartId + "," + execMsg);
        }
    }


    /**
     * 重新生成图表（异步消息队列）
     *
     * @param chartId
     * @param request
     * @return 图表id
     */
    @PostMapping("/reRry")
    public BaseResponse<BiResponse> reGenChartByAiAsyncMQ(long chartId, HttpServletRequest request) {
        Chart chart1 = chartService.getById(chartId);
        ThrowUtils.throwIf(chart1 == null, ErrorCode.PARAMS_ERROR, "要重新生成的图表不存在");
        //      sseService.sendMessage(1L,"genChartByAiAsyncMQ");
        //
        //        try {
        //            sseEmitter.send("666as6das6sda6asdds", MediaType.APPLICATION_JSON);
        //
        //        } catch (IOException e) {
        //            throw new RuntimeException(e);
        //        }

        String name = chart1.getName();
        String goal = chart1.getGoal();
        String chartType = chart1.getChartType();
        String csvString = chart1.getChartData();
        //校验参数
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "分析目标为空");
        ThrowUtils.throwIf(StringUtils.isNotBlank(name) && name.length() > 100, ErrorCode.PARAMS_ERROR, "图表名称过长");

        User loginUser = userService.getLoginUser(request);
        //限流判断,每个用户一个限流器
        redisLimiterManager.doRateLimit("reGenChartByAiAsyncMQ" + loginUser.getId());


        //用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：").append("\n");
        //拼接图标类型
        String userGoal = goal;
        if (StringUtils.isNotBlank(chartType)) {
            userGoal += goal + ",请使用" + chartType + "图标类型";
        }
        userInput.append(userGoal).append("\n");
        userInput.append("原始数据：").append("\n");
        userInput.append(csvString).append("\n");
        //修改图表状态为等待
        chart1.setStatus(ChartStatusEnum.WAIT.status);
        boolean isUpdateChart = chartService.updateById(chart1);
        ThrowUtils.throwIf(!isUpdateChart, ErrorCode.SYSTEM_ERROR, "更新图表状态为‘等待’失败");
        //将图表id发送到消息队列
        biMessageProducer.sendMessage(chart1.getId().toString());
        BiResponse biResponse = new BiResponse();
        biResponse.setChartId(chart1.getId());
        return ResultUtils.success(biResponse);
    }


    /**
     * 根据id获取图表原始数据
     *
     * @param chartId
     * @param request
     * @return 原始数据
     */
    @GetMapping("/rawData")
    public BaseResponse<List<LinkedHashMap<String, Object>>> getChartRawData(long chartId, HttpServletRequest request) {
        ThrowUtils.throwIf(chartId < 0, ErrorCode.PARAMS_ERROR);
        List<LinkedHashMap<String, Object>> maps = chartService.selectChartRawData(chartId);
        ThrowUtils.throwIf(CollUtil.isEmpty(maps), ErrorCode.SYSTEM_ERROR, "此图表原始数据不存在 chartId: " + chartId);

        return ResultUtils.success(maps);
    }

}
